import axios from 'axios'
import router from '@/router/routers'
import store from '../store'
import { Notification, MessageBox } from 'element-ui'
import { getToken } from '@/utils/auth'
import Config from '@/settings'
import Cookies from 'js-cookie'

// 提示信息显示时长
const messageDuration = 5 * 1000

// 创建axios实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // api 的 base_url
  timeout: Config.timeout // 请求超时时间
})

// request拦截器
service.interceptors.request.use(
  config => {
    let _config = config
    try {
      if (getToken()) {
        _config.headers['Authorization'] = 'bearer ' + getToken()
      }
    } catch (e) {
      console.error(e)
    }
    return _config
  },
  error => {
    Promise.reject(error)
  }
)

// response 拦截器
service.interceptors.response.use(
  response => {
    const result = response.data;
    if (result.hasOwnProperty('code') && result.hasOwnProperty('data')) {
      if (result.code === '0') {
        return result.data;
      } else {
        Notification.error({
          title: result.message,
          duration: messageDuration
        })
        return Promise.reject(new Error(result.message))
      }
    } else {
      return result;
    }
  },
  error => {
    // 兼容blob下载出错json提示
    if (error.response.data instanceof Blob && error.response.data.type.toLowerCase().indexOf('json') !== -1) {
      const reader = new FileReader()
      reader.readAsText(error.response.data, 'utf-8')
      reader.onload = function (e) {
        const errorMsg = JSON.parse(reader.result).message
        Notification.error({
          title: errorMsg,
          duration: messageDuration
        })
      }
    } else {
      if (error.response) {
        const errorMessage = error.response.data === null ? '系统内部异常，请联系网站管理员' : error.response.data.message
        if (error.toString().indexOf('Error: timeout') !== -1) {
          Notification.error({
            title: '网络请求超时',
            duration: messageDuration
          })
          return Promise.reject(error)
        }
        switch (error.response.status) {
          case 404:
            Notification.error({
              title: '很抱歉，资源未找到',
              duration: messageDuration
            })
            break
          case 403:
            router.push({ path: '/401' })
            break
          case 401:
            store.dispatch('LogOut').then(() => {
              // 用户登录界面提示
              Cookies.set('point', 401)
              location.reload()
            })
            break
          default:
            Notification.error({
              title: errorMessage,
              duration: messageDuration
            })
            break
        }
      }
    }
    return Promise.reject(error)
  }
)

export default service

